package cn.antho.org.service.impl;

import cn.antho.basic.service.impl.BaseServiceImpl;
import cn.antho.basic.util.MD5Utils;
import cn.antho.basic.util.StrUtils;
import cn.antho.org.domain.Department;
import cn.antho.org.domain.Employee;
import cn.antho.org.mapper.DepartmentMapper;
import cn.antho.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional(readOnly = true, propagation = Propagation.SUPPORTS)
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 无限级数
     * 必会写法
     * @return
     */
    @Override
    public List<Department> deptTree() {
        List<Department> allDepts = departmentMapper.findAll();
        // stream流
        Map<Long, Department> parentMap = allDepts.stream().collect(Collectors.toMap(Department::getId, e -> e));
        // 同理
        List<Department> result = new ArrayList<>();
        // 遍历
        for (Department dept : allDepts) {
            if (null == dept.getParentId()) {
                // 如果没有上级id，则自己就是老大
                result.add(dept);
            } else {
                // 有上级id，找爹
                Department parent = parentMap.get(dept.getParentId());
                if (null == parent) {
                    break ;
                }
                List<Department> children = parent.getChildren();
                children.add(dept);
            }
        }
        return result;
    }

    @Override
    public List<Employee> findByDept(Long id) {
        return departmentMapper.findByDept(id);
    }

}
